/*******************************************************************
 *
 * Copyright (C), 2020-2020, Welland, All rights reserved.
 *
 * Author      : Fengze Luo
 * Create Time : 2020-02-12
 * Version     : v0.1
 * Description : 
 *******************************************************************/
 
/*----------------------------Head file----------------------------*/
#include "hal_timer.h"
#include "user_config.h"
#include "string.h"
#include "debug.h"
#include "pwm.h"

/*----------------------------macro file---------------------------*/
#define HAL_TIMER_CH_NUM			1
#define TIMER_INTERVAL_MS(x)		(x*16)
/*----------------------------type define--------------------------*/

/*----------------------------var define---------------------------*/
static hal_timer_cb timeout_cb = NULL;
/*-------------------------func declaration------------------------*/

/*-----------------------------------------------------------------*/


void pwm_isr(void)
{
	unsigned long ulIntStatus = REG_PWM_INTR;

	REG_PWM_INTR = ulIntStatus;
	if(ulIntStatus & (0x01 << HAL_TIMER_CH_NUM))
	{
		if(timeout_cb) {
			timeout_cb();
		}
	}

	//while (REG_PWM_INTR & ulIntStatus & REG_PWM_INTR_MASK);	//Wait int_mask clear
}

void hal_timer_init(hal_timer_cb cb)
{
	timeout_cb = cb;
}

void hal_timer_start(void)
{
	uint8_t mode = 0x07;
	unsigned short end_value = TIMER_INTERVAL_MS(DISP_TIMER_INT_MS);
    unsigned short duty_cycle = TIMER_INTERVAL_MS(DISP_TIMER_INT_MS);
	
	REG_PWM_X_CNT(HAL_TIMER_CH_NUM) = 
        ((((unsigned long)duty_cycle << PWM_CNT_DUTY_CYCLE_POSI) & 0xFFFF0000UL)
       + (((unsigned long)end_value << PWM_CNT_END_VALUE_POSI) & 0x0000FFFFUL));

    REG_PWM_CTRL = (REG_PWM_CTRL & (~(0x0F << (0x04 * HAL_TIMER_CH_NUM))))
             | ((mode & 0x0F) << (0x04 * HAL_TIMER_CH_NUM));

	REG_AHB0_ICU_PWMCLKCON |= 0x01;			//Select 16MHz CLK, Must divied into two sentence.
	REG_AHB0_ICU_PWMCLKCON |= (8 << 12);	//Div CLK, Must divied into two sentence.
	REG_AHB0_ICU_INT_ENABLE |= INT_STATUS_PWM1_bit;
	ICU_PWM_CLK_PWM_X_PWD_CLEAR(HAL_TIMER_CH_NUM);			//CLK START
}

void hal_timer_stop(void)
{
	REG_AHB0_ICU_INT_ENABLE &= ~(INT_STATUS_PWM1_bit);
	ICU_PWM_CLK_PWM_X_PWD_SET(HAL_TIMER_CH_NUM);			//CLK STOP
}


